package com.csx.governance.sample.gw.controller;

import com.csx.governance.sample.gw.feign.ServiceProviderClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @author cuisongxu
 * @date 2023/4/3 9:57
 */
@RequestMapping("/gateway")
@RestController
public class GwController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WebClient.Builder clientBuilder;

    @Autowired
    private ServiceProviderClient serviceProviderClient;

    @GetMapping("/{path}")
    public String proxy(@PathVariable("path") String path) {
        String url = "http://serviceA:8001/serviceA/" + path;
        String res = restTemplate.getForObject(url, String.class);
        return res;
    }

    @GetMapping("/webClient/{path}")
    public Mono<String> proxyWebClient(@PathVariable("path") String path) {
        String url = "http://serviceA:8001/serviceA/" + path;
        String baseUrl = "http://serviceA";
        String uri = "/serviceA/" + path;
        return clientBuilder.baseUrl(baseUrl).build().get().uri(uri).retrieve().bodyToMono(String.class);
    }

    // ******************************* 测试OpenFeign ***************************************
    @GetMapping("/testAsyncFeign")
    public String testFeign(){
        CompletableFuture<String> future = serviceProviderClient.testAsyncFeign();
        String res = null;
        future.thenAccept(response -> {
            System.out.println("异步响应结果为: " + response);
        });
        try {
            res = future.get();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return "gw async feign " + " ->  \n" + res;
    }
}
